<template>
  <div class="fault-analysis-container">
    <el-page-header content="故障深度分析" style="margin-bottom: 30px;"></el-page-header>

    <!-- 故障归因看板 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card" style="padding: 20px;">
          <div slot="header">
            <span>故障类型归因</span>
          </div>
          <div id="faultPie" style="width: 100%; height: 300px;"></div>
          <div class="fault-type-desc">
            绝缘故障: {{ faultStats.insulation }} 次
            | 机械故障: {{ faultStats.mechanical }} 次
            | 外力故障: {{ faultStats.force }} 次
            | 误操作: {{ faultStats.misop }} 次
          </div>
        </el-card>
      </el-col>

      <!-- 故障影响辐射 -->
      <el-col :span="12">
        <el-card shadow="hover" class="stat-card" style="padding: 20px;">
          <div slot="header">
            <span>故障影响分析</span>
          </div>
          <el-table
              :data="faultImpactList"
              border
              style="width: 100%; margin-top: 20px;"
              height="400"
          >
            <el-table-column prop="alarm_id" label="报警ID" width="100"></el-table-column>
            <el-table-column prop="fault_type" label="故障类型" width="100"></el-table-column>
            <el-table-column prop="impact_analysis" label="影响分析" min-width="200"></el-table-column>
            <el-table-column prop="repair_cost" label="修复成本" align="right" width="120"></el-table-column>
            <el-table-column prop="loss_cost" label="损失成本" align="right" width="120"></el-table-column>
            <el-table-column prop="total_cost" label="总成本" align="right" width="120"></el-table-column>
            <el-table-column prop="analysis_time" label="分析时间" width="200"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 故障时间轴溯源 -->
    <el-card shadow="hover" class="stat-card" style="margin-top: 30px; padding: 20px;">
      <div slot="header">
        <span>故障时间轴溯源</span>
        <el-select
            v-model="selectedFaultDev"
            placeholder="选择设备"
            style="width: 200px; margin-left: 20px;"
        >
          <el-option
              v-for="dev in faultDeviceOptions"
              :key="dev.value"
              :label="dev.label"
              :value="dev.value"
          ></el-option>
        </el-select>
      </div>
      <el-timeline style="margin-top: 20px;">
        <el-timeline-item
            v-for="(event, idx) in faultTimeline"
            :key="idx"
            :timestamp="event.time"
            placement="top"
        >
          <el-card>
            <h4>{{ event.title }}</h4>
            <p>{{ event.desc }}</p>
            <p v-if="event.indicator" class="indicator-tag">
              关联指标: {{ event.indicator }}
            </p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// 导入API模块（根据实际项目路径调整）
import { api } from '@/api'

export default {
  name: 'FaultDeepAnalysis',
  data() {
    return {
      faultStats: {
        insulation: 0,  // 初始值设为0
        mechanical: 0,
        force: 0,
        misop: 0
      },
      faultImpactList: [], // 初始化为空数组
      faultDeviceOptions: [
        { label: '110kV#005变压器', value: 'dev005' },
        { label: '10kV#042开关柜', value: 'dev042' }
      ],
      selectedFaultDev: 'dev005',
      faultTimeline: [
        {
          time: '2024-03-12 14:23',
          title: '首次检测异常',
          desc: '油色谱分析乙炔含量超标',
          indicator: '乙炔含量: 12μL/L（阈值10μL/L）'
        },
        // 其他时间轴事件...
      ],
      pieChart: null,
      loading: false, // 新增加载状态
      apiError: null   // 新增API错误信息
    }
  },
  created() {
    // 新增：组件创建时获取数据
    this.fetchFaultData()
  },
  mounted() {
    this.initFaultPie()
  },
  methods: {
    // 新增：API数据获取方法
    async fetchFaultData() {
      this.loading = true
      try {
        // 模板：调用后端API获取数据
        // 替换api.fault.getDeepAnalysis为实际API方法
        const response = await api.fault.getDeepAnalysis()
        
        if (response.data.code === 200) {
          // 模板：根据实际API返回结构调整赋值
          this.faultStats = response.data.stats
          this.faultImpactList = response.data.impactList
          
          // 数据更新后重绘图表
          this.initFaultPie()
        } else {
          this.$message.error(response.data.message || '数据获取失败')
        }
      } catch (error) {
        console.error('API调用失败:', error)
        this.apiError = error.message
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    initFaultPie() {
      // 如果图表已存在则更新，否则初始化
      if (!this.pieChart) {
        this.pieChart = echarts.init(document.getElementById('faultPie'))
      }
      
      // 使用当前数据更新图表
      this.pieChart.setOption({
        title: { text: '', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['绝缘故障', '机械故障', '外力故障', '误操作']
        },
        series: [{
          name: '故障类型',
          type: 'pie',
          radius: ['40%', '70%'],
          data: [
            { value: this.faultStats.insulation, name: '绝缘故障' },
            { value: this.faultStats.mechanical, name: '机械故障' },
            { value: this.faultStats.force, name: '外力故障' },
            { value: this.faultStats.misop, name: '误操作' }
          ]
        }]
      })
    }
  },
  beforeDestroy() {
    if (this.pieChart) this.pieChart.dispose()
  }
}
</script>

<style scoped>
.fault-analysis-container {
  padding: 30px;
}
.stat-card {
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.fault-type-desc {
  text-align: center;
  margin-top: 20px;
  color: #666;
}
.indicator-tag {
  color: #f56c6c;
  margin-top: 5px;
}
</style>